package spider

import (
	"encoding/json"

	"io/ioutil"
	"net/http"
	"priceApi/utils"
	"strconv"

	"github.com/astaxie/beego"
)

type AliyunRateBody struct {
	Money    string `json:"money"`
	Ret_code int64  `json:"ret_code"`
}

type AliyunRate struct {
	Body AliyunRateBody `json:"showapi_res_body"`
}

func GetAliyunRate() float64 {
	var jsondata AliyunRate
	client := &http.Client{}
	req, err := http.NewRequest("GET", "http://ali-waihui.showapi.com/waihui-transform?fromCode=USD&money=1&toCode=CNY", nil)
	if err != nil {
		utils.PostError("获取阿里云汇率出错,http.NewRequest", err.Error())
		return 0
	}
	req.Header.Set("Authorization", "APPCODE a23f595d761843c7a6daf19018810ced")

	resp, err := client.Do(req)
	if err != nil {
		utils.PostError("获取阿里云汇率出错,resp, err := client.Do(req)", err.Error())
		return 0
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		utils.PostError("获取阿里云汇率出错,body, err := ioutil.ReadAll(resp.Body)", err.Error())
		return 0
	}
	json.Unmarshal([]byte(body), &jsondata)
	beego.Debug("获取阿里云汇率数据", jsondata)
	if jsondata.Body.Ret_code == 0 {
		v2, _ := strconv.ParseFloat(jsondata.Body.Money, 64)

		return v2

	} else {
		utils.PostError("获取阿里云汇率出错,jsondata.Body.Ret_code != 0", "jsondata.Body.Ret_code != 0")
		return 0
	}
	return 0
}
